<template>
  <el-dialog :visible.sync="visible" width="600px" :title="!dataForm.id ? $t('leave') : $t('leave')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="耳号" prop="earmark">
            <!--<pig-tree :props="props"
              :options="optionData"
              :value="valueId"
              :filter="0"
              :clearable="isClearable"
              :accordion="isAccordion"
              @getValue="getValue($event)"></pig-tree>-->
            <el-autocomplete v-model="dataForm.earmark" :fetch-suggestions="queryPigAsync" placeholder="耳号"></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="离场日期" prop="outDate">
            <el-date-picker
              v-model="dataForm.outDate"
              align="right"
              type="date"
              placeholder="离场日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="离场类型" prop="outType">
            <RenSelect dictType="leave_type" placeholder="请选择"
                       v-model="dataForm.outType"></RenSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="重量" prop="weight">
            <el-input v-model="dataForm.weight" placeholder="重量"><i slot="suffix" style="font-style:normal;margin-right: 10px;">kg</i></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="金额" prop="price">
            <el-input v-model="dataForm.price" placeholder="金额"><i slot="suffix" style="font-style:normal;margin-right: 10px;">元</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="操作人" prop="operator">
            <UserSelect v-model="dataForm.operator"></UserSelect>
        </el-form-item>
        </el-col>
      </el-row>
      <el-form-item size='small' label="备注" prop="remark">
        <el-input type="textarea" :rows="2" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-divider></el-divider>
      <el-row>
        <el-col :span="4">
          <el-checkbox label="连续录入" v-model="continues"></el-checkbox>
        </el-col>
        <el-col :span="20">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>/* eslint-disable */
import debounce from 'lodash/debounce'
import PigTree from '@/views/modules/components/pig-tree'
export default {
  data () {
    return {
      houses:{},
      pigs: [],
      visible: false,
      continues: true,
      dataForm: {
        id: '',
        outDate: '',
        outType: '',
        price: '',
        unitPrice: '',
        weight: '',
        operator: '',
        houseId: '',
        earmark: '',
        remark: ''
      },
      pickerOptions: {
        disabledDate: (time) => {
            var year1=new Date(time).getFullYear();
				    var year2=new Date().getFullYear();
            return time.getTime() > Date.now() || (year2-year1 >= 5);
        }
      }
    }
  },
  computed: {
    dataRule () {
      return {
        outDate: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        earmark: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    PigTree
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
        this.getHouses()
        this.getPigs()
      })
    },
    getPigs () {
      let that = this;
      that.pigs = [];
      this.$http.get(`/stock/pig/getAllEarMarks`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(earmark){
          that.pigs.push({value: earmark});
        });
        this.$forceUpdate()
      }).catch(() => {})   
    },
    queryPigAsync(queryString, cb) {
      var pigs = this.pigs;
      var results = queryString ? pigs.filter(this.createStateFilter(queryString)) : pigs;
      cb(results);
    },
    createStateFilter(queryString) {
      return (earmark) => {
        let equal = (earmark.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
        return equal;
      };
    },
    getHouses () {
      let that = this;
      this.$http.get(`/basic/house/all`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(house){
          that.houses[house.id] = house;
        });
        this.$forceUpdate()
      }).catch(() => {})   
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/stock/pig/out/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http['post']('/stock/pig/out/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              if(!this.continues) {
                this.visible = false
              } else {
                for(let key in this.dataForm) {
                  this.dataForm[key] = '';
                }
              }
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
    .el-input, .el-select {
      width: 180px;
    }

    .el-textarea {
      width: 460px;
    }
</style>
